package com.mobile.liuyi_s.orderlunch;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.mobile.liuyi_s.orderlunch.BaseActivity;
import com.mobile.liuyi_s.orderlunch.MyApplication;
import com.mobile.liuyi_s.orderlunch.R;
import com.mobile.liuyi_s.orderlunch.Utils.Utils;
import com.mobile.liuyi_s.orderlunch.entity.MyUser;
import com.mobile.liuyi_s.orderlunch.entity.Order;
import com.mobile.liuyi_s.orderlunch.fragment.CountFragment;
import com.mobile.liuyi_s.orderlunch.fragment.MeFragment;
import com.mobile.liuyi_s.orderlunch.fragment.OrderFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener{

    private MeFragment mMeFragment;
    private OrderFragment mOrderFragment;
    private CountFragment mSetFragment;

    private static final String TAG = "MainActivity";
    private static final int QUERY_ORDR_INFO = 123;

    private String currUserName;
    private boolean isOrdered = true;
    private MyApplication mApplication;

    private static final int BACK_PRESSED = 2;
    private static boolean isExit = false;
    private static final String TAG_FINISH = "finish";
    private static Handler mBackPressedHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    //override this method to quit app
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            boolean isFinish = intent.getBooleanExtra(TAG_FINISH, false);
            if (isFinish) {
                finish();
//                android.os.Process.killProcess(android.os.Process.myPid());
//                System.exit(0);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            mBackPressedHandler.sendEmptyMessageDelayed(BACK_PRESSED, 2000);
        } else {
            finish();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyUser myUser = BmobUser.getCurrentUser(MyUser.class);
        mApplication = ((MyApplication) getApplication());
        mApplication.userLogin(myUser);
        currUserName = BmobUser.getCurrentUser(MyUser.class).getUsername();

        Log.d(TAG, "onCreate: " + currUserName);
        //query order info from DB
        queryOrderInfo();
        mApplication.setOrdered(isOrdered);
        Log.d(TAG, "onCreate: 传入application的isOrdered:" + mApplication.getIsOrdered());
        getServerTime();

        final int sdk = Build.VERSION.SDK_INT;
        if (sdk >= Build.VERSION_CODES.KITKAT) {
            //TODO
        }
        setContentView(R.layout.activity_main);

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ts = manager.beginTransaction();
        Fragment fragment = manager.findFragmentByTag("me");
        RadioGroup tabBar = (RadioGroup) findViewById(R.id.tab_bar);
        if (tabBar != null) {
            tabBar.check(R.id.rbtn_order);
            tabBar.setOnCheckedChangeListener(this);
        }

        if (fragment == null) {
            mMeFragment = new MeFragment();
        } else {
            mMeFragment = ((MeFragment) fragment);
        }

        fragment = manager.findFragmentByTag("order");
        if (fragment == null) {
            mOrderFragment = new OrderFragment();
            ts.replace(R.id.fragment_container, mOrderFragment, "order");
            ts.commit();
        } else {
            mOrderFragment = ((OrderFragment) fragment);
            ts.replace(R.id.fragment_container, mOrderFragment, "order");
            ts.commit();
        }

        fragment = manager.findFragmentByTag("set");
        if (fragment == null) {
            mSetFragment = new CountFragment();
        } else {
            mSetFragment = ((CountFragment) fragment);
        }
    }

    private void getServerTime() {
        Bmob.getServerTime(new QueryListener<Long>() {

            @Override
            public void done(Long time, BmobException e) {
                if(e==null){
                    SimpleDateFormat formatter = new SimpleDateFormat(
                            "yyyy-MM-dd HH:mm");
                    String times = formatter.format(new Date(time * 1000L));
                    Toast.makeText(MainActivity.this, "当前服务器时间为:" + times, Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "获取服务器时间失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();

                }
            }

        });
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkId) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ts = manager.beginTransaction();
        switch (checkId) {
            case R.id.rbtn_me:
                ts.replace(R.id.fragment_container, mMeFragment, "me");
                break;
            case R.id.rbtn_order:
                ts.replace(R.id.fragment_container, mOrderFragment, "order");
                break;
            case R.id.rbtn_set:
                ts.replace(R.id.fragment_container, mSetFragment, "set");
                break;
            default:
                break;
        }
        ts.commit();
    }

    private void queryOrderInfo() {
        Utils utils = new Utils();
        BmobQuery<Order> queryUser = new BmobQuery<>();
        queryUser.addWhereEqualTo("orderUser", currUserName);
        BmobQuery<Order> queryYear = new BmobQuery<>();
        queryYear.addWhereEqualTo("orderYear", utils.getLocacYear());
        BmobQuery<Order> queryMonth = new BmobQuery<>();
        queryMonth.addWhereEqualTo("orderMonth", utils.getLocacMonth());
        BmobQuery<Order> queryDay = new BmobQuery<>();
        queryDay.addWhereEqualTo("orderDay", utils.getLocacDay());
        ArrayList<BmobQuery<Order>> queries = new ArrayList<>();
//        Log.d(TAG, "queryOrderInfo: " + "用户名："+username+
//                " 年："+utils.getLocacYear()+" 月："+utils.getLocacMonth()+" 日：" + utils.getLocacDay());
        queries.add(queryUser);
        queries.add(queryYear);
        queries.add(queryMonth);
        queries.add(queryDay);
        BmobQuery<Order> mainQuery = new BmobQuery<>();
        mainQuery.and(queries);
        mainQuery.findObjects(new FindListener<Order>() {
            @Override
            public void done(List<Order> list, BmobException e) {
                if (e == null) {
                    Message message = mHandler.obtainMessage();
                    message.what = QUERY_ORDR_INFO;
                    message.obj = list;
                    mHandler.sendMessage(message);
                    Log.d(TAG, "done: 方法中查询到的订单列表size："+list.size());
                } else {
                    Log.d(TAG, "done: 复合查询用户订单信息失败");
                }
            }
        });
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case QUERY_ORDR_INFO:
                    List<Order> orderList = (List<Order>) msg.obj;
                    if (orderList.size() == 0) {
                        isOrdered = false;
                    } else {
                        isOrdered = true;
                    }
                    Log.d(TAG, "handleMessage: orderList:"+ orderList.size());
                    Log.d(TAG, "handleMessage: 查询用户是否订餐"+isOrdered);
                    break;
                default:
                    break;
            }
        }
    };


}
